<script lang="ts" setup>
import { ElNotification } from "element-plus";

import settingComponents from "./areaComponents";
import { zoonType } from "./components/config";
import SetTemplate from "./step/SetTemplate.vue";
import SetBasic from "./step/SetBasic.vue";
import AuditDialog from "@/components/audit/AuditDialog.vue";
import PreviewQrcode from "./components/PreviewQrcode.vue";
import {
  getTemplatePatternApi,
  getCurrencysApi,
  activityPageApi,
  getTemplateInfoApi,
  editActBaseInfoApi,
  editActPageApi,
  addPageAreaApi,
  getListStoreApi,
  getTaskListApi,
  addActivityApi,
  getActivityByIdApi,
  editActApi,
  activityPreview,
} from "@/api/activity";
import { deepClone, debounce, newRandomUid } from "@/utils";
import areaList from "./components/area";

const route = useRoute(),
  router = useRouter(),
  store = useStore(),
  internalInstance = getCurrentInstance();

const iframeLoading = ref(true),
  iframeUrl = (window as any).VUE_APP_URL[import.meta.env.MODE]
    .activePreviewPath + store.state.user.merchant.merchantCode,
  activityDetail = ref<any>({}),
  saveloading = ref(false),
  currentTab = ref("0"),
  iframeReady = ref(false),
  templateReady = ref(false),
  zoneList = ref<Array<any>>([]),
  currencyList = ref<Array<any>>([]),
  merchantList = ref<Array<any>>([]),
  templatePage = ref<any>({}),
  activityList = ref<Array<any>>([]),
  taskList = ref<Array<any>>([]),
  templateConfig = ref<Array<any>>([]),
  currentPage = ref(""),
  auditForm: any = ref({}),
  showPreview = ref(false),
  qrcodeURL = ref(""),
  showAuditDialog = ref(false);

const iframeRef = ref(),
  basicRef = ref(),
  templateRef = ref<Array<any>>([]),
  zoneRef = ref<Array<any>>([]);

const filters = internalInstance?.appContext.config.globalProperties.$filters;

const activityId = computed(() => {
  if (route.name === "ActivityEdit") return route.params.id || "";
  return "";
});

const copyId = computed(() => {
  if (route.name === "ActivityAdd") return route.params.copyId || "";
  return "";
});

const templateId = computed(() => {
  if (route.name === "ActivityAdd") return route.params.id || "";
  return "";
});

const isCopyed = computed(() => {
  return copyId.value !== "";
});

const activityReadonly = computed(() => {
  // 活动详情
  if (route.params.mode === "detail") return true;
  // 编辑审核中
  if (
    activityDetail.value.checkStatus === 1 &&
    activityDetail.value.status === 2
  )
    return true;
  return false;
});

// 编辑审核中
const activityAudit = computed(() => {
  if (
    route.params.mode === "edit" &&
    activityDetail.value.checkStatus === 1 &&
    activityDetail.value.status === 2
  )
    return true;
  return false;
});

// 商户id
const merchantId = computed(() => {
  return store.state.user.merchantId || "";
});

const homePageConfig = computed(() => {
  let homeConfig = templateConfig.value.find(
    (item) => item.pageType === "Home"
  );
  return homeConfig?.configList || [];
});

// 当前模板页面索引
const pageIndex = computed(() => {
  let index = templateConfig.value.findIndex(
    (item) => item.uid === currentPage.value
  );
  return index;
});

const showBack = computed(() => {
  return history.length > 0;
});

watch([iframeReady, templateReady], ([ready1, ready2]: Array<boolean>) => {
  if (ready1 && ready2) {
    iframeLoading.value = false;
    toUpdateIframeMessage();
  }
});

const toUpdateIframeMessage = debounce(
  async () => {
    if ((iframeReady.value && templateReady.value) === false) return;
    console.log("商户端发送消息");
    let areas = zoneList.value.map((zone) => ({
      pageFlag: zone.pageArea.pageFlag,
      ...zone,
    }));
    iframeRef.value.contentWindow.postMessage(
      {
        method: "updateIframeMessage",
        pageName: currentPage.value,
        params: {
          pageConfig: deepClone(pageTemplate()),
          zoneList: deepClone(areas),
        },
      },
      "*"
    );
  },
  300,
  false
);

const pageTemplate = () => {
  let page = templateConfig.value.find(
    (item) => item.uid === currentPage.value
  );
  if (page) return page.configList;
  return [];
};

// 切换tab
const changeTabPane = (activeName: string, oldActiveName: string) => {
  return true;
  if (activityId.value === "" || activityReadonly.value === true) return true;
  return new Promise((resolve, reject) => {
    ElMessageBox.confirm("是否要保存当前更改？", "温馨提示", {
      confirmButtonText: "保存",
      cancelButtonText: "不保存",
      type: "warning",
    })
      .then(async () => {
        try {
          await saveTemplate(oldActiveName, activeName);
          resolve("");
        } catch (e) {
          reject();
        }
      })
      .catch(() => {
        resolve("");
      });
  });
};

// 切换模板页面
const pageChange = (name: string) => {
  toUpdateIframeMessage();
};

// 活动分步保存
const saveTemplate = async (oldTabName: string, nextTabName?: string) => {
  saveloading.value = true;
  return new Promise(async (resolve, reject) => {
    try {
      let rs = null;
      // 保存活动基础配置
      if (Number(currentTab.value) == 0) {
        let baseForm = await basicRef.value.submit();
        rs = await editActBaseInfoApi(baseForm);
      }
      // 保存活动页面配置
      else if (Number(currentTab.value) == 1) {
        let { pageConfig, subPageConfig }: any = await saveTemplatePage();

        rs = await editActPageApi({
          ...templatePage.value,
          actId: activityDetail.value.id,
          pageConfig: JSON.stringify(pageConfig),
          subPageConfig: JSON.stringify(subPageConfig),
        });
      }
      // 保存活动区域配置
      else {
        let zoneInfo = await zoneRef.value[Number(oldTabName) - 2].submit();
        rs = await addPageAreaApi(zoneInfo);
      }
      saveloading.value = false;

      if (rs.code == 200) {
        if (nextTabName === undefined) {
          ElNotification.success({
            message: "保存成功",
          });
          goBack(false);
        }
        resolve("");
      } else reject();
    } catch (e) {
      saveloading.value = false;
      ElNotification.error({
        message: e || "请检查活动配置",
      } as any);
      reject();
    }
  });
};

// 活动提交审核成功
const submitAudit = () => {
  goBack(false);
};

// 活动整体保存
const saveActivity = async (type: string) => {
  let currentName = 0;
  try {
    let activityInfo = await basicRef.value.submit();
    currentName = 1;
    let { pageConfig, subPageConfig }: any = await saveTemplatePage();

    let pageAreas = [],
      actSignConfigs: any = [],
      actShareConfig: any = null,
      voteConfigEntity: any = null,
      actTaskConfigs: any = [],
      actEntryConfigs: any = [],
      actQuestionConfigs: any = [],
      actSeckillConfigs: any = [],
      prizeAreas: any = [];
    for (let i = 0; i < zoneRef.value.length; i++) {
      currentName = 2 + i;
      let zoneInfo = await zoneRef.value[i].submit();
      if (!zoneInfo) return false;

      pageAreas.push(zoneInfo.pageArea);
      prizeAreas = prizeAreas.concat(zoneInfo.prizeAreas);
      if (zoneInfo.actSignConfig) actSignConfigs.push(zoneInfo.actSignConfig);
      if (zoneInfo.actShareConfig) actShareConfig = zoneInfo.actShareConfig;
      if (zoneInfo.actTaskConfig) actTaskConfigs.push(zoneInfo.actTaskConfig);
      if (zoneInfo.actEntryConfig)
        actEntryConfigs.push(zoneInfo.actEntryConfig);
      if (zoneInfo.actQuestionConfig)
        actQuestionConfigs.push(zoneInfo.actQuestionConfig);
      if (zoneInfo.voteConfigEntity)
        voteConfigEntity = zoneInfo.voteConfigEntity;
      if (zoneInfo.actSeckillConfig)
        //清除复制的相关id
        if (isCopyed.value) {
          zoneInfo.actSeckillConfig.seckillAreas.forEach((i) => {
            i.actId = undefined
            i.prizeArea = undefined
          })
        }
      actSeckillConfigs.push(zoneInfo.actSeckillConfig);
    }

    let params = {
      activityInfo,
      pageAreas,
      prizeAreas,
      templatePage: {
        ...templatePage.value,
        pageConfig: JSON.stringify(pageConfig),
        subPageConfig: JSON.stringify(subPageConfig),
      },
      actSignConfigs,
      actShareConfig,
      actTaskConfigs,
      actEntryConfigs,
      actQuestionConfigs,
      voteConfigEntity,
      actSeckillConfigs,
    };
    // 预上线活动编辑审核activityDetail.value.status == 2
    if (activityDetail.value.status == 2) {
      let href = window.location.href.split("#/")[0];
      if (import.meta.env.MODE === "development") {
        href = "https://marketingtest.lianhaikeji.com/merchant/";
      }
      // 提交审核
      auditForm.value = {
        submitTitle: `【${activityDetail.value.name}】编辑审核`,
        relationName: activityDetail.value.name,
        relationId: activityDetail.value.id,
        pageRouter: `${href}#/activity/list/detail/${activityDetail.value.id}`,
        relationType: "activity_modify",
        submitInfo: JSON.stringify({
          活动名称: activityInfo.name,
          开始时间: filters.dateFormat(activityInfo.startTime),
          结束时间: filters.dateFormat(activityInfo.endTime),
        }),
        businessParams: JSON.stringify(params),
      };
      showAuditDialog.value = true;
      return;
    }
    saveloading.value = true;
    let api = !activityDetail.value.id ? addActivityApi : editActApi;
    const rs = await api(params);
    if (rs.code == 200) {
      ElNotification.success({
        message: "保存成功",
      });
      saveloading.value = false;
      if (rs.payload.id) {
        activityDetail.value.id = rs.payload.id;
        zoneList.value = [];
        getActivityDetail(rs.payload.id);
      }
      // 保存并退出
      if (type === "back") goBack(false);
      // 保存并预览
      else if (type === "preview") {
        let longUrl: any = await getPreviewAddress(activityDetail.value.id)
        qrcodeURL.value = longUrl;
        showPreview.value = true;
        history.replaceState(
          null,
          "活动模板",
          `#/activity/list/edit/${activityDetail.value.id}`
        );
      }
    }
  } catch (e) {
    currentTab.value = currentName.toString();
    ElNotification.error({
      message: e || "请检查配置项",
    } as any);
  }
  saveloading.value = false;
};

// 获取预览地址
const getPreviewAddress = async (id: any) => {
  let res = await activityPreview({ id: id })
  if (res.code === 200) {
    return res.payload.previewUrl
  }
  return ''
}

// 模板信息保存
const saveTemplatePage = () => {
  return new Promise(async (resolve, reject) => {
    try {
      let autoPopupNum=1 //记录自定义弹窗是否开启自动开关，只能有一个开启
      let _templateConfig = deepClone(templateConfig.value);
      let _pageConfig = [],
        _subPageConfig = [];
      for (let i = 0; i < templateRef.value.length; i++) {
        _templateConfig[i].configList = await templateRef.value[i].submit();
        _templateConfig[i].configList.forEach((item: any) => {
          if (item.type === "Popup" || item.pageConfig.$mode === "popup") {
            item.pageConfig.$show = false;
          }
          if(item.type==='CustomPopup'&&item.$autoShow){
            autoPopupNum++
          }
        });

        if (_templateConfig[i].pageType === "Home")
          _pageConfig = _templateConfig[i].configList;
        else _subPageConfig.push(_templateConfig[i]);
      }
      if(autoPopupNum>2){
        reject('只能开启一个自动弹窗,请检查后重新操作');
      }
      resolve(
        deepClone({ pageConfig: _pageConfig, subPageConfig: _subPageConfig })
      );
    } catch (e) {
      reject(e || "请检查页面设计");
    }
  });
};

// 新建活动获取模板信息
const getTemplateDetail = async () => {
  iframeLoading.value = true;
  let type = route.query.type;
  let api = type === "private" ? getTemplateInfoApi : getTemplatePatternApi;
  const rs = await api({
    id: templateId.value,
  } as any);
  if (rs.code == 200) {
    templatePage.value = {
      patternId: rs.payload.id,
    };

    formatTemplateConfig(
      rs.payload.templateConfig,
      rs.payload.subTemplateConfig
    );

    // 初始化区域配置
    for (let i = 0; i < templateConfig.value.length; i++) {
      for (let j = 0; j < templateConfig.value[i].configList.length; j++) {
        let $el = templateConfig.value[i].configList[j];
        if (zoonType[$el.type] !== undefined) {
          zoneList.value.push({
            pageArea: {
              name: `${$el.name}配置`,
              type: zoonType[$el.type].type,
              pageFlag: $el.pageConfig.$pageFlag,
              subType: $el.type,
            },
          });
        }
      }
    }
    activityDetail.value = {
      name: rs.payload.name,
      status: 0,
    };
    templateReady.value = true;
  }
};

const refreshRegionConfig = (uid: any) => {
  console.log('[ uid ]', uid)
  console.log('[ zoneList.value ]', zoneList.value)
  console.log('[ templateConfig.value ]', templateConfig.value)
  for (let i = 0; i < templateConfig.value.length; i++) {
    for (let j = 0; j < templateConfig.value[i].configList.length; j++) {
      let $el = templateConfig.value[i].configList[j];
      if (zoonType[$el.type] !== undefined && $el.uid === uid) {
        zoneList.value.push({
          pageArea: {
            name: `${$el.name}配置`,
            type: zoonType[$el.type].type,
            pageFlag: $el.pageConfig.$pageFlag,
            subType: $el.type,
          },
        });
      }
    }
  }
}

// 获取活动详情
const getActivityDetail = async (actId: any = null) => {
  let id = actId || activityId.value || copyId.value;
  const rs = await getActivityByIdApi({ id });
  console.log("[ rs ]", rs);
  if (rs.code == 200) {
    // const actInfo = copyActDetail(rs.payload);
    activityDetail.value = rs.payload.actInfo;
    if (!actId && isCopyed.value) {
      delete activityDetail.value.id;
      activityDetail.value.status = 0;
    }
    templatePage.value = {
      ...rs.payload.templatePage,
      actId: isCopyed.value ? undefined : rs.payload.templatePage.actId,
      id: isCopyed.value ? undefined : rs.payload.templatePage.id,
    };

    // 模板配置
    formatTemplateConfig(
      rs.payload.templatePage.pageConfig,
      rs.payload.templatePage.subPageConfig
    );

    formatAreaData(rs.payload);
    templateReady.value = true;
  }
};

// 格式化模板配置
const formatTemplateConfig = (pageConfig: any, subPageConfig: any) => {
  let _templateConfig = pageConfig ? JSON.parse(pageConfig) : [];
  let _subPageConfig = subPageConfig ? JSON.parse(subPageConfig) : [];
  _subPageConfig.forEach((item: any) => {
    if (!item.uid) item.uid = newRandomUid();
  });

  templateConfig.value = [
    {
      pageType: "Home",
      pageName: "首页",
      uid: newRandomUid(),
      configList: _templateConfig,
    },
    ..._subPageConfig,
  ];
  currentPage.value = templateConfig.value[0].uid;
};

// 复制活动统一过滤id
const copyActDetail = (actInfo: any) => {
  if (isCopyed.value) {
    for (let key in actInfo) {
      // 活动基本信息
      if (key === "actInfo") {
        actInfo[key].id = undefined;
        actInfo[key].status = 0;
      }
      // 区域公共配置
      else if (key === "pageAreas") {
        actInfo[key].forEach((area: any) => {
          area.id = undefined;
          area.actId = undefined;
        });
      }
      // 奖池配置
      else if (key === "prizeAreas") {
        actInfo[key].forEach((area: any) => {
          area.uid = area.id;
          area.id = undefined;
          area.actId = undefined;
          area.prizeInfos.forEach((prize: any) => {
            prize.uid = prize.id;
            prize.id = undefined;
            prize.areaId = undefined;
            prize.actId = undefined;
            prize.prizeSpecifications.forEach((spec: any) => {
              spec.uid = spec.id;
              spec.id = undefined;
              spec.actId = undefined;
            });
            prize.childPrizes.forEach((childPrize: any) => {
              childPrize.uid = childPrize.id;
              childPrize.id = undefined;
              childPrize.actId = undefined;
              childPrize.areaId = undefined;
              childPrize.prizeSpecifications.forEach((spec: any) => {
                spec.uid = spec.id;
                spec.id = undefined;
                spec.actId = undefined;
              });
            });
          });
        });
      }
      // 各区域定制化配置
      else {
        if (actInfo[key] instanceof Array) {
          actInfo[key].forEach((config) => {
            config.id = undefined;
            config.actId = undefined;
            config.actRewards = formatReward(
              config.actRewards,
              actInfo.prizeAreas
            );
          });
        } else {
          actInfo[key].id = undefined;
          actInfo[key].actId = undefined;
        }
      }
    }
  } else return actInfo;
};

// 格式化活动区域配置
const formatAreaData = (detail: any) => {
  for (let i = 0; i < templateConfig.value.length; i++) {
    for (let j = 0; j < templateConfig.value[i].configList.length; j++) {
      let $el = templateConfig.value[i].configList[j];
      if (zoonType[$el.type] !== undefined) {
        let pageFlag = $el.pageConfig.$pageFlag;
        let pageArea = detail.pageAreas.find(
          (item: any) => item.pageFlag === pageFlag
        );
        let zone: any = {
          pageArea: {
            ...pageArea,
            hasTicket: isCopyed.value ? 0 : pageArea.hasTicket,
            name: `${$el.name}配置`,
            type: zoonType[$el.type].type,
            pageFlag: pageFlag,
            subType: $el.type,
            id: isCopyed.value ? undefined : pageArea.id,
            actId: isCopyed.value ? undefined : pageArea.actId,
            checkStatus: isCopyed.value ? 0 : pageArea.checkStatus,
          },
        };

        let prizeAreas = detail.prizeAreas.filter(
          (item: any) => item.pageFlag === pageFlag
        );
        if (prizeAreas) zone.prizeAreas = formatPrizeAreas(prizeAreas);

        let actSignConfig = (detail.actSignConfigs || []).find(
          (item: any) => item.pageFlag === pageFlag
        );
        if (actSignConfig)
          zone.actSignConfig = formatSignConfig(actSignConfig, zone.prizeAreas);

        let actShareConfig =
          (detail.actShareConfig || {}).pageArea === pageFlag
            ? detail.actShareConfig
            : null;
        if (actShareConfig)
          zone.actShareConfig = formatShareConfig(
            actShareConfig,
            zone.prizeAreas
          );
        // actTaskConfig
        let actTaskConfig = (detail.actTaskConfigs || []).find(
          (item: any) => item.pageFlag === pageFlag
        );
        if (actTaskConfig)
          zone.actTaskConfig = formatTaskConfig(actTaskConfig, zone.prizeAreas);
        let actEntryConfig = (detail.actEntryConfigs || []).find(
          (item: any) => item.pageFlag === pageFlag
        );
        if (actEntryConfig)
          zone.actEntryConfig = formatEntryConfig(
            actEntryConfig,
            zone.prizeAreas
          );

        let actQuestionConfig = (detail.actQuestionConfigs || []).find(
          (item: any) => item.pageFlag === pageFlag
        );
        if (actQuestionConfig)
          zone.actQuestionConfig = formatAnswerConfig(
            actQuestionConfig,
            zone.prizeAreas
          );

        let voteConfigEntity =
          (detail.voteConfigEntity || {}).pageFlag === pageFlag
            ? detail.voteConfigEntity
            : null;
        if (voteConfigEntity)
          zone.voteConfigEntity = formatVoteConfig(
            voteConfigEntity,
            zone.prizeAreas
          );

        // actSeckillConfig
        let actSeckillConfig = (detail.actSeckillConfigs || []).find(
          (item: any) => item.pageFlag === pageFlag
        );
        console.log(
          "detail.actSeckillConfigs",
          JSON.parse(JSON.stringify(detail.actSeckillConfigs))
        );
        if (actSeckillConfig)
          zone.actSeckillConfig = formatSeckillConfig(
            actSeckillConfig,
            zone.prizeAreas
          );
        console.log("zone", zone);
        zoneList.value.push(zone);
      }
    }
  }
};

// 格式化报名
const formatEntryConfig = (actEntryConfig: any, prizeAreas: Array<any>) => {
  return !isCopyed.value
    ? (() => {
      actEntryConfig.fieldConfig = JSON.parse(actEntryConfig.fieldConfig);
      return actEntryConfig;
    })()
    : (() => {
      let data = {
        ...actEntryConfig,
        actId: undefined,
        id: undefined,
      };
      data.fieldConfig = JSON.parse(data.fieldConfig);
      return data;
    })();
};
// 格式化奖池
const formatPrizeAreas = (prizeAreas: Array<any>) => {
  return !isCopyed.value
    ? prizeAreas
    : prizeAreas.map((item: any, index1: number) => {
      return {
        ...item,
        actId: undefined,
        id: undefined,
        uid: item.id,
        prizeInfos: !item.prizeInfos
          ? item.prizeInfos
          : item.prizeInfos.map((prize: any, index2: number) => {
            return {
              ...prize,
              actId: undefined,
              id: undefined,
              uid: prize.id,
              areaId: undefined,
              stock: prize.stockTotal,
              prizeSpecifications: !prize.prizeSpecifications
                ? prize.prizeSpecifications
                : prize.prizeSpecifications.map(
                  (spec: any, index3: number) => {
                    return {
                      ...spec,
                      originalStock: 0,
                      originalStockTotal: 0,
                      stock: spec.totalStock,
                      num: spec.totalStock,
                      actId: undefined,
                      id: undefined,
                      uid: spec.id,
                    };
                  }
                ),
              childPrizes: !prize.childPrizes
                ? prize.childPrizes
                : prize.childPrizes.map((child: any, index3: number) => {
                  return {
                    ...child,
                    actId: undefined,
                    id: undefined,
                    areaId: undefined,
                    uid: child.id,
                    prizeSpecifications: child.prizeSpecifications.map(
                      (spec: any, index4: number) => {
                        return {
                          ...spec,
                          actId: undefined,
                          id: undefined,
                          uid: spec.id,
                        };
                      }
                    ),
                  };
                }),
            };
          }),
      };
    });
};

// 格式化签到配置
const formatSignConfig = (actSignConfig: any, prizeAreas: Array<any>) => {
  return !isCopyed.value
    ? actSignConfig
    : (() => {
      return {
        ...actSignConfig,
        actId: undefined,
        id: undefined,
        isCopy: true,
        itemList: actSignConfig.itemList.map((reward: any) => {
          if (reward.rewardEntity.rewardType === "PRIZE") {
            let pool = prizeAreas.find(
              (area: any) => area.uid == reward.rewardEntity.prizeArea
            );
            let prize = pool.prizeInfos.find(
              (prize: any) => prize.uid == reward.rewardEntity.prizeId
            );
            let spec = prize.prizeSpecifications.find(
              (spec: any) => spec.uid == reward.rewardEntity.prizeSpec
            );
            return {
              ...reward,
              id: undefined,
              isCopy: true,
              rewardEntity: {
                ...reward.rewardEntity,
                id: undefined,
                actId: undefined,
                prizeArea: pool.uid,
                prizeId: prize.uid,
                prizeSpec: spec.uid,
              },
            };
          } else if (reward.rewardEntity.rewardType === "LOTTERY") {
            let pool = prizeAreas.find(
              (area: any) => area.uid == reward.rewardEntity.lotteryArea
            );
            return {
              ...reward,
              isCopy: true,
              id: undefined,
              rewardEntity: {
                ...reward.rewardEntity,
                id: undefined,
                actId: undefined,
                lotteryArea: pool.uid,
              },
            };
          } else {
            return {
              ...reward,
              isCopy: true,
              id: undefined,
              rewardEntity: {
                ...reward.rewardEntity,
                id: undefined,
                actId: undefined,
              },
            };
          }
        }),
      };
    })();
};

// 格式化分享配置
const formatShareConfig = (actShareConfig: any, prizeAreas: Array<any>) => {
  return !isCopyed.value
    ? actShareConfig
    : (() => {
      return {
        ...actShareConfig,
        actId: undefined,
        id: undefined,
        rrewardList: formatReward(actShareConfig.rewardList, prizeAreas),
      };
    })();
};

// 格式化任务配置
const formatTaskConfig = (actTaskConfig: any, prizeAreas: Array<any>) => {
  return !isCopyed.value
    ? actTaskConfig
    : (() => {
      return {
        ...actTaskConfig,
        actId: undefined,
        id: undefined,
        rewardList: formatReward(actTaskConfig.rewardList || [], prizeAreas),
        taskList: actTaskConfig.taskList.map((item: any, index: number) => {
          return {
            ...item,
            id: undefined,
            configId: undefined,
            uid: `task-${index}`,
            rewardList: formatReward(item.rewardList || [], prizeAreas),
          };
        }),
      };
    })();
};

// 格式化答题配置
const formatAnswerConfig = (actAnswerConfig: any, prizeAreas: Array<any>) => {
  return !isCopyed.value
    ? actAnswerConfig
    : (() => {
      return {
        ...actAnswerConfig,
        actId: undefined,
        id: undefined,
        rewardConfigList: actAnswerConfig.rewardConfigList.map(
          (item: any) => {
            return {
              ...item,
              rewardList: formatReward(item.rewardList || [], prizeAreas),
            };
          }
        ),
      };
    })();
};

// 格式化投票配置
const formatVoteConfig = (voteConfigEntity: any, prizeAreas: Array<any>) => {
  return !isCopyed.value
    ? voteConfigEntity
    : (() => {
      return {
        ...voteConfigEntity,
        actId: undefined,
        id: undefined,
        rewardList: formatReward(
          voteConfigEntity.rewardList || [],
          prizeAreas
        ),
      };
    })();
};
// 格式化秒杀配置
const formatSeckillConfig = (actSeckillConfig: any, prizeAreas: Array<any>) => {
  return !isCopyed.value
    ? actSeckillConfig
    : (() => {
      return {
        ...actSeckillConfig,
        actId: undefined,
        id: undefined,
        seckillAreas: actSeckillConfig.seckillAreas.map(
          (item: any, index: number) => {
            return {
              ...item,
              id: undefined,
              seckillId: undefined,
              uid: `seckill-${index}`,
            };
          }
        ),
      };
    })();
};

// 格式化奖励
const formatReward = (rewardList: Array<any>, prizeAreas: Array<any>) => {
  return rewardList.map((reward: any) => {
    if (reward.rewardType === "PRIZE") {
      let pool = prizeAreas.find(
        (area: any) => (area.id || area.uid) == reward.prizeArea
      );
      let prize = pool.prizeInfos.find(
        (prize: any) => (prize.id || prize.uid) == reward.prizeId
      );
      let spec = prize.prizeSpecifications.find(
        (spec: any) => (spec.id || spec.uid) == reward.prizeSpec
      );
      return {
        ...reward,
        actId: undefined,
        id: undefined,
        targetId: undefined,
        prizeArea: pool.id || pool.uid,
        prizeId: prize.id || prize.uid,
        prizeSpec: spec.id || spec.uid,
      };
    } else if (reward.rewardType === "LOTTERY") {
      let pool = prizeAreas.find(
        (area: any) => (area.id || area.uid) == reward.lotteryArea
      );
      return {
        ...reward,
        actId: undefined,
        id: undefined,
        targetId: undefined,
        lotteryArea: pool.id || pool.uid,
      };
    } else if (reward.rewardType === "TICKET") {
      return {
        ...reward,
        actId: undefined,
        id: undefined,
        targetId: undefined,
        ticketAct:
          reward.ticketAct == reward.actId ? "local" : reward.ticketAct,
      };
    } else {
      return {
        ...reward,
        actId: undefined,
        id: undefined,
        targetId: undefined,
      };
    }
  });
};

// 获取代币类型
const getCurrency = async () => {
  const rs: any = await getCurrencysApi({ currentPage: 1, showCount: -1 });
  if (rs.code == 200) {
    currencyList.value = rs.payload;
  }
};

// 获取商家列表
const getMerchantList = async () => {
  const rs = await getListStoreApi();
  if (rs.code == 200) {
    merchantList.value = rs.payload.map((item: any) => ({
      ...item,
      label: item.storeName,
      value: item.storeUserId,
    }));
  }
};

// 获取活动列表
// const getActivityList = async () => {
//   const rs = await activityPageApi({
//     showCount: -1,
//     currentPage: 1,
//     status: 1,
//   });
//   if (rs.code == 200) {
//     activityList.value = rs.payload;
//   }
// };

// 获取任务类型
const getTaskType = async () => {
  const rs = await getTaskListApi({ showCount: -1, currentPage: 1 });
  if (rs.code == 200) {
    taskList.value = rs.payload;
  }
};

const handleMessage = (event: any) => {
  var data = event.data;
  console.log("接收到活动消息：", data);
  switch (data.method) {
    case "pageOk":
      iframeReady.value = true;
      break;
    case "configUpdate":
      templateConfig.value[pageIndex.value].configList = data.params;
      break;
    case "generateCoverOk":
      basicRef.value.form.generateLoading = false;
      basicRef.value.form.coverUrl = data.params;
      break;
    case "configDelete":
      templateRef.value[pageIndex.value].delete(data.params);
      break;
    case "jumpTo":
      templateRef.value[pageIndex.value].jumpTo(data.params);
      break;
    default:
      break;
  }
};

const goBack = (tip = true) => {
  if (activityReadonly.value === true) {
    router.back();
  } else if (tip) {
    ElMessageBox.confirm(`确定放弃当前编辑内容？`, "温馨提示", {
      confirmButtonText: "确认",
      cancelButtonText: "取消",
      type: "warning",
    }).then(async () => {
      router.replace({ name: "ActivityList" });
    });
  } else {
    router.replace({ name: "ActivityList" });
  }
};

// 撤销操作
const undo = () => {
  iframeRef.value.contentWindow.postMessage(
    {
      method: "configUndo",
      pageName: currentPage.value,
    },
    "*"
  );
};

// 恢复操作
const restore = () => {
  iframeRef.value.contentWindow.postMessage(
    {
      method: "configRestore",
      pageName: currentPage.value,
    },
    "*"
  );
};

const generatePoster = () => {
  (iframeRef as any).value.contentWindow.postMessage(
    {
      method: "generateCover",
    },
    "*"
  );
};

provide("generatePoster", generatePoster);
provide("activityBaseInfo", activityDetail);
provide("currencyList", currencyList);
provide("merchantList", merchantList);
provide("zoneList", zoneList);
// provide("activityList", activityList);
provide("taskList", taskList);
provide("activityId", activityId);
provide("activityReadonly", activityReadonly);
provide("pageConfig", homePageConfig);

onMounted(async () => {
  window.addEventListener("message", handleMessage, false);
  if (activityId.value !== "" || copyId.value !== "") {
    await getActivityDetail();
  } else await getTemplateDetail();
  getCurrency();
  getMerchantList();
  // getActivityList();
  getTaskType();
});

onBeforeUnmount(() => {
  window.removeEventListener("message", handleMessage, false);
});
</script>
<template>
  <MainContent class="activity-content" :title="activityReadonly
    ? '活动详情'
    : $route.name === 'ActivityAdd' && activityDetail.id
      ? '编辑活动'
      : $route.meta.title
    " :back="showBack" :backFunc="true" @back="goBack(true)">
    <template #extra v-if="!activityReadonly">
      <el-button @click="goBack(true)">取消</el-button>
      <el-button v-if="activityDetail.status !== 2" type="primary" :loading="saveloading"
        @click="saveActivity('preview')">保存并预览</el-button>
      <el-button type="primary" :loading="saveloading" @click="saveActivity('back')">保存并退出</el-button>
      <!-- <el-button
        v-else
        type="primary"
        @click="saveTemplate(currentTab)"
        :loading="saveloading"
        >保存</el-button
      > -->
    </template>
    <div class="container">
      <div class="phone hiddenScroll">
        <div class="toolbar">
          <div v-if="!activityReadonly">
            <el-button link title="撤销" @click="undo">
              <svg t="1670379255853" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg"
                p-id="2681" width="20" height="20">
                <path
                  d="M457.1 614.5c-111.6-93.8-216.4-181.9-323.7-272.1 106.6-89.6 211.5-177.6 321.5-270v125.1c59.9 7.5 116.5 10.8 171.3 22.2 113.9 23.6 204.7 78.9 244.3 196.5 57.2 169.7-10.6 357.8-163 451.4-2.1 1.3-4.7 2-10.1 4.2 20.4-24.9 40.1-46.1 56.7-69.6 32.8-46.2 51.9-97.6 54.1-154.8 2-51.6-20.9-89.1-64.1-115.3-50.5-30.7-107.1-41.6-164.5-46.4-39.8-3.3-80-0.6-122.5-0.6v129.4z"
                  p-id="2682" fill="#bfbfbf"></path>
              </svg>
            </el-button>
            <el-button link title="恢复" @click="restore">
              <svg t="1673234360734" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg"
                p-id="4965" width="25" height="25">
                <path
                  d="M512 371.2V261.973333a25.6 25.6 0 0 1 40.106667-20.906666L819.2 426.666667a25.6 25.6 0 0 1 0 42.666666l-267.093333 186.453334a25.6 25.6 0 0 1-40.106667-20.906667V567.466667a25.173333 25.173333 0 0 0-26.88-25.6 341.333333 341.333333 0 0 0-301.653333 263.68 336.64 336.64 0 0 1 304.64-409.173334 25.173333 25.173333 0 0 0 23.893333-25.173333z"
                  fill="#bfbfbf" p-id="4966"></path>
              </svg>
            </el-button>
          </div>
          <el-tabs v-model="currentPage" type="card" @tab-change="pageChange">
            <el-tab-pane v-for="item in templateConfig" :key="item.uid" :label="item.pageName" :name="item.uid">
            </el-tab-pane>
          </el-tabs>
        </div>
        <div class="phoneContent" v-loading="iframeLoading">
          <iframe v-show="iframeReady" ref="iframeRef" class="iframe" :src="`${iframeUrl}#/design`"
            frameborder="0"></iframe>
          <div class="cover" :title="!activityReadonly && activityId !== '' && currentTab != '1'
            ? '切换到页面设计进行编辑'
            : ''
            " v-if="activityReadonly"></div>
        </div>
      </div>
      <div class="tabs-container">
        <el-tabs v-model="currentTab" type="border-card" :before-leave="changeTabPane">
          <el-tab-pane label="基础配置">
            <SetBasic ref="basicRef" :detail="activityDetail"></SetBasic>
          </el-tab-pane>
          <el-tab-pane label="页面设计">

            <template v-for="(config, index) in templateConfig">

              <div v-show="currentPage === config.uid">
                <SetTemplate :ref="(el) => {
                  if (el) templateRef[index] = el;
                }
                  " v-model:model-value="config.configList" original="merchant" :pageList="templateConfig"
                  @change="toUpdateIframeMessage" @refreshRegionConfig="refreshRegionConfig"></SetTemplate>
              </div>
            </template>
          </el-tab-pane>
          <el-tab-pane v-for="(pane, index) in zoneList" :label="pane.pageArea.name">
            <component :is="settingComponents[pane.pageArea.type]" :ref="(el) => {
              if (el) {
                zoneRef[index] = el;
              }
            }
              " v-model="zoneList[index]" @change="toUpdateIframeMessage" />
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>
  </MainContent>
  <!-- 编辑审核弹窗 -->
  <AuditDialog :title="`【${auditForm.relationName}】编辑审核`" v-model:show="showAuditDialog" v-model="auditForm"
    @confirm="submitAudit" />
  <!-- 活动预览 -->
  <PreviewQrcode v-model:show="showPreview" :link="qrcodeURL" />
</template>
<style lang="scss" scoped>
.activity-content {
  :deep(.all-content) {
    min-height: calc(100vh - 108px);
    height: calc(100vh - 108px);

    .content-slot-bg {
      min-height: auto;
      height: 100%;
    }
  }
}

.container {
  display: flex;
}

.phone {
  flex-shrink: 0;
  margin-right: 20px;

  .toolbar {

    // display: flex;
    // justify-content: space-between;
    // align-items: center;
    .toolbar-item {
      font-size: 12px;
      cursor: pointer;
    }
  }

  :deep(.el-tabs) {
    max-width: 330px;

    .el-tabs__header {
      margin-bottom: 0;
    }
  }

  .phoneContent {
    display: block;
    width: 332px;
    height: 627px;
    border: 1px solid #efefef;
    position: relative;
    box-sizing: border-box;

    .iframe {
      width: 100%;
      height: 100%;
    }

    .cover {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      cursor: no-drop;
    }
  }
}

.tabs-container {
  flex: 1;
  height: 690px;
  width: 0;

  .el-tabs {
    height: 100%;

    :deep(.el-tabs__content) {
      height: calc(100% - 65px);
      overflow-y: auto;
    }
  }
}
</style>
